<template>
    <div>
        <!--面包屑导航栏区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--卡片区域-->
        <el-card>
            <!--添加角色按钮-->
            <el-row>
                <el-col><el-button type="primary" @click="showAddDialog">添加角色</el-button></el-col>
            </el-row>
            <!--角色列表区域-->
                 <el-table :data="rolesList" style="width: 100%" border stripe>
                     <el-table-column  type="expand" label="权限页">
                         <template slot-scope="scope">
                             <el-row v-for='(item1, index1) in scope.row.children' :key='item1.id' :class="['bdborder',index1 === 0 ? 'tpborder' :'', 'vcenter']">
                                 <!--一级权限列-->
                                 <el-col :span="5">
                                     <el-tag closable>{{item1.authName}}</el-tag>
                                     <i class="el-icon-caret-right"></i>
                                 </el-col>
                                 <!--二级和三级权限列-->
                                 <el-col :span="19">
                                     <el-row v-for="(item2, index2) in item1.children" :key="item2.id" :class="[index2 === 0 ? '' : 'tpborder', 'vcenter']">
                                         <!--二级权限列-->
                                         <el-col :span="6">
                                            <el-tag closable type="success">{{item2.authName}}</el-tag>
                                            <i class="el-icon-caret-right"></i>
                                        </el-col>
                                         <!--三级权限列-->
                                        <el-col :span="18">
                                                    <el-tag v-for="item3 in item2.children" :key="item3.id" closable type="warning" @close="deleteRights(scope.row, item3)">{{item3.authName}}</el-tag>
                                        </el-col>
                                     </el-row>
                                 </el-col>
                             </el-row>
                         </template>
                     </el-table-column>
                    <el-table-column  type="index" label="排序"></el-table-column>
                    <el-table-column  prop="roleName" label="角色名称"></el-table-column>
                    <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                        <!--使用作用域插槽-->
                    <el-table-column label="操作" width="300px">
                        <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
                        <el-button size="mini"  type="danger" icon="el-icon-delete" @click="DeleteDialog(scope.row.id)">删除</el-button>
                        <el-button size="mini"  type="warning" icon="el-icon-setting" @click="showRightsDialog(scope.row)">分配权限</el-button>
                        </template>
                    </el-table-column>
                </el-table>
        </el-card>
        <!--添加角色对话框-->
        <el-dialog
            title="添加角色"
            :visible.sync="addDialogVisible"
            width="50%"
            @close="addDialogClosed">
            <!--验证表单-->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
            <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible= false">取 消</el-button>
            <el-button type="primary" @click="addRoles">确 定</el-button>
            </span>
        </el-dialog>
        <!--编辑角色对话框-->
        <el-dialog
            title="编辑角色"
            :visible.sync="editDialogVisible"
            width="50%">
            <!--验证表单-->
            <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
            <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible= false">取 消</el-button>
            <el-button type="primary" @click="editRoles">确 定</el-button>
            </span>
        </el-dialog>
        <!--分配权限对话框-->
        <el-dialog
            title="分配权限"
            :visible.sync="rightsDialogVisible"
            width="50%"
            @close="resetRightsForm">
            <el-tree
            :data="rightsForm"
            :props="defaultProps"
            show-checkbox
            default-expand-all
            node-key="id"
            :default-checked-keys="defaultKeys"
            ref="treeRef">
            </el-tree>
            <span slot="footer" class="dialog-footer">
            <el-button @click="rightsDialogVisible= false">取 消</el-button>
            <el-button type="primary" @click="addRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data () {
        return {
            rolesList: [],
            addForm: {
                roleName: '',
                roleDesc: ''
            },
            addDialogVisible: false,
            addFormRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 1, max: 10, message: '长度在3到10个字符', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入角色描述', trigger: 'blur' }
                ]
            },
                editForm: {},
                editDialogVisible: false,
                rightsDialogVisible: false,
                rightsForm: [],
                defaultProps: {
                    children: 'children',
                    label: 'authName'
                },
                defaultKeys: [],
                roleId: 0
        }
    },
    created () {
        this.getRolesList()
    },
    methods: {
        // 获取角色列表
        async getRolesList () {
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
            this.rolesList = res.data
        },
        // 打开添加角色对话框
        showAddDialog () {
            this.addDialogVisible = true
        },
        // 提交添加的角色信息
        addRoles () {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.post('roles', this.addForm)
                if (res.meta.status !== 201) this.$message.error('添加角色失败')
                this.$message.success('添加角色成功')
                this.addDialogVisible = false
                this.getRolesList()
            })
        },
        addDialogClosed () {
            this.$refs.addFormRef.resetFields()
        },
        // 打开编辑角色对话框
        async showEditDialog (id) {
            this.editDialogVisible = true
            const { data: res } = await this.$http.get('roles/' + id)
            if (res.meta.status !== 200) return this.$message.error('查询角色信息失败')
            this.editForm = res.data
        },
        // 提交编辑好的角色信息
        editRoles () {
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, this.editForm)
                if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
                this.$message.success('修改用户信息成功')
                this.getRolesList()
                this.editDialogVisible = false
            })
        },
        // 删除角色
        async DeleteDialog (id) {
            const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(err => err)
        if (result !== 'confirm') return this.$message.error('取消删除角色')
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除用户信息失败')
            this.$message.success('删除用户信息成功')
            this.getRolesList()
         },
         // 删除权限
         async deleteRights (row, item) {
            const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(err => err)
        if (result !== 'confirm') return this.$message.info('取消删除角色')
        const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${item.id}`)
        if (res.meta.status !== 200) return this.$message.error('删除权限失败')
            this.$message.success('删除权限成功')
            row.children = res.data
         },
         // 打开权限分配对话框
         async showRightsDialog (row) {
            this.roleId = row.id
            this.rightsDialogVisible = true
            const { data: res } = await this.$http.get('rights/tree')
            if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
            this.rightsForm = res.data
            this.getLeafKeys(row, this.defaultKeys)
         },
         // 获取所选角色的权限列表（通过递归函数的形式，获取角色下所有三级权限的ID，并保存到defaultKeys数组中
         getLeafKeys (node, arr) {
            if (!node.children) return arr.push(node.id)
            node.children.forEach(item => this.getLeafKeys(item, arr))
         },
         // 权限分配对话框关闭时，重置权限列表
         resetRightsForm () {
             this.defaultKeys = []
         },
         // 提交分配的角色权限
         async addRights () {
             const keys = [
                 ...this.$refs.treeRef.getCheckedKeys(),
                 ...this.$refs.treeRef.getHalfCheckedKeys()
             ]
             const keyStr = keys.join(',')
             const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
                rids: keyStr
             })
             if (res.meta.status !== 200) return this.$message.error('提交分配角色失败')
             this.$message.success('提交分配角色成功')
             this.getRolesList()
             this.rightsDialogVisible = false
         }
    }
}
</script>
<style lang="less" scoped>
.el-tag{
    margin:7px
}
.tpborder{
    border-top: 1px solid #eee;
}
.bdborder{
    border-bottom:1px solid #eee; ;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>
